<?php
/**
 * Created by Yevgen Vershynin.
 * User: Yevgen Vershynin
 * Description: Implements connection to DataBase
 */
class DbComponent
{
    private $dbHost = "localhost";
    private $dbName = "yv_rest_service";
    private $dbUserName = "root";
    private $dbPass = "softjourn";

    private $connection;

    private static $dbInstance;

    private function __construct()
    {
        //Create connection to DB according to settings.
        $this->connection = new mysqli($this->dbHost, $this->dbUserName, $this->dbPass, $this->dbName);

        return $this->connection;
    }

    public static function getInstance()
    {
        if(!self::$dbInstance)
        {
            self::$dbInstance = new DbComponent();
        }

        return self::$dbInstance;
    }

    public function queryAll($sqlQuery)
    {
        //Make query for sql.
        $result = $this->connection->query($sqlQuery);

        $allRows = array();
        //Fetch all rows and save it to the array
        while ($row = $result->fetch_assoc())
        {
            $allRows[] = $row;
        }

        return $allRows;
    }

    public function queryRow($sqlQuery)
    {
        //Fetch only first row from the result oft the query
        $result = $this->connection->query($sqlQuery);

        return $result->fetch_assoc();
    }

    public function insert($insertQuery)
    {
        //Perform insert and Update queries.
        $result = $this->connection->query($insertQuery);

        return $this->connection->affected_rows;
    }
}
